import ScorePanel from "../modules/ScorePanel"
import Food from "../modules/Food"
import Snack from "../modules/Snack"

class Control{
    food:Food
    snack:Snack
    scorepanel:ScorePanel
    direction = ''
    isLive = true
    constructor(){
        this.food = new Food()
        this.snack = new Snack()
        this.scorepanel = new ScorePanel()
        //初始化游戏，调用则游戏开始
        this.init()
    }
    //定义一个初始化函数
    init(){
        /* 
            在这里this会出现问题,因为在这里this是由document调用所以this指向document
            解决办法:
                - 可以使用箭头函数
                - bind()
        */
        // document.addEventListener('keydown',(event:KeyboardEvent)=>{
        //     this.SnackDirection(event)
        // })
        document.addEventListener('keydown',this.SnackDirection.bind(this))
        this.run()
    }

    //键盘按下事件
    SnackDirection(event:KeyboardEvent){
        // 修改direction属性
        this.direction = event.key
    }

    //让蛇跑起来
    run(){
        let x = this.snack.X
        let y = this.snack.Y
        //判断方向
        switch(this.direction){
            case "ArrowUp" : y -= 10; break;
            case "ArrowDown" : y += 10; break;
            case "ArrowLeft" : x -= 10; break;
            case "ArrowRight": x += 10; break;
        }

        this.checkFood(x,y)

       try {
            // 修改蛇的位置
            this.snack.X = x
            this.snack.Y = y
       } catch (error) {
           alert(error)
           this.isLive = false
       }

        this.isLive && setTimeout(()=>{
            this.run()
        }, 100-(this.scorepanel.num2 - 1)*10);
    }


    //检查是否吃到东西
    checkFood(x:number,y:number){
        if(this.food.X === x && this.food.Y === y)
        {
            //进入判断表示吃到了东西
            this.food.foodRandom()
            this.snack.addBody()
            this.scorepanel.addScore
        }
    }



}

export default Control
